import type { ComputedRef, Ref } from "vue";
import type { CascaderItemTreeListResult } from "@/api/types";
import type { UseBaseTable } from "@/composables";
import { ElMessage } from "element-plus";
import { computed, reactive } from "vue";
import { cascaderItemApi } from "@/api";
import { useBaseTable } from "@/composables";
import { $t } from "@/plugins/i18n";
import { apiCall } from "@/utils/http/apiCall";

interface UseCascaderItemTable extends Omit<UseBaseTable<CascaderItemTreeListResult>, "tablePage" | "tableData"> {
    /** 查询表单 */
    tableQuery: { name: string | null };
    /** 过滤后的数据 */
    tableFilteredData: ComputedRef<CascaderItemTreeListResult[]>;
    /** 获取表格数据 */
    fetchTableData: () => void;
    /** 删除字典项 */
    handleDelete: (code: string, typeId: string) => void;
}

export function useCascaderItemTable(typeCode: Ref<string>): UseCascaderItemTable {
    const { tableLoading, tableData } = useBaseTable<CascaderItemTreeListResult>();

    /** 查询表单 */
    const tableQuery = reactive<{ name: string | null }>({
        name: null,
    });

    /** 过滤后的数据 */
    const tableFilteredData = computed(() => {
        const name = tableQuery.name || "";
        if (!name.trim()) {
            return tableData.value;
        }
        // Recursive filter function for tree data
        const filterTree = (nodes: CascaderItemTreeListResult[]): CascaderItemTreeListResult[] => {
            return nodes.reduce((acc, node) => {
                const matches = node.name.toLowerCase().includes(name.toLowerCase());
                const children = node.children ? filterTree(node.children as CascaderItemTreeListResult[]) : null;

                if (matches || (children && children.length > 0)) {
                    acc.push({
                        ...node,
                        children: children && children.length > 0 ? children : null,
                    });
                }
                return acc;
            }, [] as CascaderItemTreeListResult[]);
        };

        return filterTree(tableData.value);
    });

    /** 获取表格数据 */
    function fetchTableData(): void {
        tableLoading.value = true;
        apiCall(
            () => cascaderItemApi.listTree(typeCode.value),
            (data) => {
                tableData.value = data;
            },
            {
                onFinally: () => {
                    tableLoading.value = false;
                },
            },
        );
    }

    /** 删除字典项 */
    function handleDelete(code: string, typeId: string): void {
        apiCall(
            () => cascaderItemApi.remove(code, typeId),
            (data, resp) => {
                ElMessage.success($t(resp.message));
                fetchTableData();
            },
        );
    }

    return {
        tableLoading,
        tableQuery,
        tableFilteredData,
        fetchTableData,
        handleDelete,
    };
}
